package com.ujs.edu.medicine.controller;

import com.auth0.jwt.JWT;
import com.ujs.edu.medicine.dao.*;
import com.ujs.edu.medicine.dataobject.*;
import com.ujs.edu.medicine.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
public class DoctorController {

    @Autowired
    private YunjiayiUserMapper yunjiayiUserMapper;
    @Autowired
    private TableChatMesMapper tableChatMesMapper;
    @Autowired
    private YunjiayiMessageMapper yunjiayiMessageMapper;
    @Autowired
    private TableConsultDUMapper tableConsultDUMapper;
    @Autowired
    private YunjiayiNoticeMapper yunjiayiNoticeMapper;
    @Autowired
    private HttpServletRequest request;
    private String gettoken() {
        return request.getHeader("Authorization");
    }

    /*获取医生列表*/
    @GetMapping("/api/doctor/list")
    public Result getdoctorlist() {

        Result result=new Result();
        JSONObject object=null;
        List<Object> list=new ArrayList<>();

        List<YunjiayiUser>  users=yunjiayiUserMapper.selectByidcard(4);
        Author author=null;

        try{
            for (YunjiayiUser user:users){
                if (user.getStatusID()!=0&&user.getStatusID()!=1&&user.getStatusID()!=2) {
                    object = new JSONObject();
                    author = new Author();

                    author.setId(user.getUser_Id());
                    author.setAvatar(user.getAvatar());
                    author.setRealname(user.getRealname());

                    object.put("author", author);
                    object.put("unit", user.getUnit());
                    object.put("abstract", user.getContent());
                    object.put("status_id", user.getStatusID());

                    list.add(object);
                }
            }

            result.setCode(0);
            result.setMessage("查询成功");
            result.setData(list);
        }catch (Exception e){
            result.setCode(0);
            result.setMessage("查询失败");
        }

        return result;
    }


    /*发起对话*/
    @RequestMapping("/api/doctor/catch")
    public Result catchDoctor(@RequestBody JSONObject object){
        Result result=new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            e.printStackTrace();
        }
        //创建聊天id
        //给通知消息发送一条信息，给回证信息发送一条信息
        YunjiayiNotice notice=new YunjiayiNotice();
        TableConsultDU tableConsultDU=new TableConsultDU();
        YunjiayiUser doctor=yunjiayiUserMapper.selectByPrimaryKey(object.getInteger("doctorID"));


        tableConsultDU.setContent(object.getString("content"));
        tableConsultDU.setFromuserid(myuserid);
        tableConsultDU.setDoctorid(object.getInteger("doctorID"));
        tableConsultDU.setReceive(0);
        tableConsultDU.setFiles(object.getJSONArray("files").toString());

        int insercons=tableConsultDUMapper.insert(tableConsultDU);
        if (insercons!=0){
            notice.setFormuserid(6);
            notice.setTouserid(myuserid);
            String content="您刚才给"+doctor.getRealname()+"医生发送了会诊请求，请注意查收。";
            notice.setContent(content);

            int insernotice=yunjiayiNoticeMapper.insert(notice);
            if (insernotice!=0){
                result.setCode(0);
                result.setMessage("发送成功");
            }else {
                result.setCode(1);
                result.setMessage("发送失败");
            }
        }else {
            result.setCode(1);
            result.setMessage("发送请求失败");
        }

        return result;
    }


    /*修改医生状态*/
   @PutMapping("/api/doctor/status")
    public Result putstatus(@RequestBody Map<String,Integer> map)
   {
       Result result=new Result();
       String token=gettoken();
       int myuserid=0;
       try {
           myuserid=JWT.decode(token).getClaim("id").asInt();
       }catch (Exception e){
           result.setCode(1);
           result.setMessage("您还没有登陆，请登录");
           return result;
       }
       YunjiayiUser user1= yunjiayiUserMapper.selectByPrimaryKey(myuserid);
       user1.setStatusID(map.get("statusID"));
       int tip=yunjiayiUserMapper.updateByPrimaryKey(user1);
       result.setCode(tip);
       result.setMessage(tip != 0 ? "修改成功" : "修改失败");
       return result;
   }


   /*会诊消息列表*/
    @RequestMapping("/api/message/doctor")
    public Result consultInfo(){
        Result result=new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您还没有登陆，请登录");
            return result;
        }

        System.out.println(myuserid);

        List<TableConsultDU>tableConsultDUS=tableConsultDUMapper.selectBydoctorId(myuserid);

        System.out.println(tableConsultDUS.size());

        try {
            List<String>list=new ArrayList<>();
            for (TableConsultDU tableConsultDU:tableConsultDUS){
                tableConsultDU.setAuthor(yunjiayiUserMapper.selectPartInfo(tableConsultDU.getFromuserid()));
                tableConsultDU.setAbstracttest(tableConsultDU.getContent());

               tableConsultDU.setFiles1(JSONObject.parseArray(tableConsultDU.getFiles()));
            }
            result.setData(tableConsultDUS);
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("出现错误，请重试");
            return result;
        }

        return result;
    }


    /*应答会诊消息*/
    @RequestMapping(value = "/api/message/agree",method = RequestMethod.POST)
    public Result responseConsult(@RequestBody JSONObject object){
        Result result=new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }

        TableConsultDU tableConsultDU=tableConsultDUMapper.selectByPrimaryKey(object.getInteger("id"));

        if (object.getBoolean("isAgree")==true){
            tableConsultDU.setReceive(1);
        }else {
            tableConsultDU.setReceive(0);
        }

        int updateconsult=tableConsultDUMapper.updateByPrimaryKey(tableConsultDU);

        YunjiayiNotice notice=new YunjiayiNotice();
        if (updateconsult!=0){
            String content=yunjiayiUserMapper.selectRealName(tableConsultDU.getDoctorid())+"医生，已经同意你的会诊请求";
            notice.setContent(content);
            notice.setTouserid(tableConsultDU.getDoctorid());
            notice.setFormuserid(tableConsultDU.getFromuserid());
            notice.setIsagree(1);

            int insertNotice=yunjiayiNoticeMapper.insert(notice);

            if (insertNotice!=0){
                result.setCode(0);
                result.setMessage("应答成功");
            }else {
                result.setCode(1);
                result.setMessage("应答失败");
            }
        }else {
            result.setCode(1);
            result.setMessage("更新应答信息失败");
        }

        YunjiayiMessage message=new YunjiayiMessage();
        if (updateconsult!=0){
            String content="我已经同意你的会诊申请，请说明您的问题";
            message.setContent(content);
            message.setFromuserid(tableConsultDU.getDoctorid());
            message.setTouserid(tableConsultDU.getFromuserid());
            message.setMessagestatus("未读");
            message.setIsfile(0);
            TableChatMes tableChatMes=tableChatMesMapper.selectByFromUserIDAndTouserId(tableConsultDU.getDoctorid(),tableConsultDU.getFromuserid());
            if (tableChatMes!=null){
                message.setChatid(tableChatMes.getChatid());
            }else {
                tableChatMes=new TableChatMes();

                tableChatMes.setFromuserid(tableConsultDU.getDoctorid());
                tableChatMes.setTouserid(tableConsultDU.getFromuserid());

                int insertchat=tableChatMesMapper.insert(tableChatMes);
            }

            result.setCode(0);
            result.setMessage("成功");
        }else {
            result.setCode(1);
            result.setMessage("失败");
        }


        return result;
    }


    /*通知消息列表*/
    @RequestMapping("/api/message/notice")
    public Result getNoticeList(){
        Result result=new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            e.printStackTrace();
        }

        List<YunjiayiNotice>notices=yunjiayiNoticeMapper.getNotic(myuserid);

        try {
            for (YunjiayiNotice notice:notices){
                notice.setAuthor(yunjiayiUserMapper.selectPartInfo(notice.getTouserid()));
                notice.setAbstracttest(notice.getContent());
            }
            result.setCode(0);
            result.setMessage("查询成功");
            result.setData(notices);
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("查询失败");
        }

        return result;
    }
}
